import Vue from 'vue'
import { message } from 'ant-design-vue'

Vue.directive('copy', {
  bind (el) {
    bindCopyEl(el)
  }
})

function bindCopyEl (el) {
  setTimeout(() => {
    const preBlocks = el.querySelectorAll('.v-show-content pre')
    preBlocks.forEach((pre) => {
      const hljs = pre.querySelector('.hljs')
      const bgColor = hljs ? getComputedStyle(hljs).background : ''
      const expandBtn = `<div class="code-block-extension-header" style="background: ${bgColor}">
          <i class="expand-icon ri-arrow-down-s-fill"></i>
          <span class="copy-code-btn">code copy</span>
        <div/>`
      pre.insertAdjacentHTML('afterbegin', expandBtn)
      const copyButton = pre.querySelector('.copy-code-btn')
      const expanIcon = pre.querySelector('.expand-icon')
      expanIcon.onclick = function (e) {
        const classList = Array.from(e.target.classList)
        if (classList.includes('ri-arrow-down-s-fill')) {
          hljs.style.height = '0px'
          e.target.classList.remove('ri-arrow-down-s-fill')
          e.target.classList.add('ri-arrow-right-s-fill')
        } else {
          hljs.style.height = 'auto'
          e.target.classList.remove('ri-arrow-right-s-fill')
          e.target.classList.add('ri-arrow-down-s-fill')
        }
      }
      copyButton.onclick = async function () {
        try {
          await navigator.clipboard.writeText(
            pre.querySelector('code').innerText
          )
          message.success('复制成功')
        } catch (error) {
          console.log(error)
        }
      }
    })
  })
}
